package com.uxsino.simo.indicator.retractor;

import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.Map.Entry;

public class SNMPFDBListRetractor extends ListValueRetractor {

    private static Logger logger = LoggerFactory.getLogger(SNMPFDBListRetractor.class);
    @SuppressWarnings("unchecked")
    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {

        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
        if (obj == null) {
            return records;
        }
        Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) obj;
        // 严格规定，cmd中的oid才能被使用
        int size = 0;
        ColumnEntry tempEntry = null;
        for (ColumnEntry entry : columnEntries) {
            if (map.containsKey(entry.index)) {
                Map<String, String> indexMap = map.get(entry.index);// field
                // 对应的oid
                if (indexMap.size() > size) {
                    size = indexMap.size();
                    tempEntry = entry;
                }
            }
        }

        if (tempEntry == null) {
            return records;
        }

        Map<String, String> maxMap = map.get(tempEntry.index);// field 对应的oid
        int valueSize = maxMap.size();
        int index = 0;
        for (Entry<String, String> maxEntry : maxMap.entrySet()) {
            index++;
            String key = maxEntry.getKey().trim();
            String sign = key.replace(tempEntry.index + ".", "");// index
            Map<String, Object> temp = new HashMap<String, Object>();
            boolean emptyValue = true;
            for (ColumnEntry entry : columnEntries) {
                Object value = null;
                if (entry.equals(tempEntry)) {
                    value = tempEntry.retractor.retract(entity, ctxt, qt, maxEntry.getValue());
                } else {
                    if (map.containsKey(entry.index)) {
                        Map<String, String> indexMap = map.get(entry.index);// field
                                                                            // 对应的oid
                        if (indexMap.size() == 1) { // get类型
                            for (Entry<String, String> entry_value : indexMap.entrySet()) {
                                value = entry.retractor.retract(entity, ctxt, qt, entry_value.getValue());
                            }
                        } else {
                            if (entry.index.endsWith(".")) {

                                value = entry.retractor.retract(entity, ctxt, qt, indexMap.get(entry.index + sign));
                            } else {
                                value = entry.retractor.retract(entity, ctxt, qt, indexMap.get(entry.index + "." + sign));
                            }
                        }
                    }
                }
                if (value != null) {
                    emptyValue = false;
                }
                if(entry.source==null || (entry.source!=null && !entry.source.equals("key"))){
                    temp.put(entry.field.getName(), value);
                }else{
                    if(entry.sub!=null){
                        String[] sub = entry.sub.split(",");
                        String[] k = sign.split("\\.");
                        int starIndex = Integer.parseInt(sub[0]);
                        int len = Integer.parseInt(sub[1]);
                        if((starIndex+len)>k.length){
                            logger.info("截取的长度:{} 超过key数组的长度:{}",starIndex+len,k.length);
                        }else{
                            String[] strings = arraySub(k, starIndex, len);
                            //截取Mac地址，转为十六进制
                            if(entry.format!=null && entry.format.equals("mac")){
                                if(strings.length!=6){
                                    logger.info("截取的key无法转为Mac地址:{}",Arrays.toString(strings));
                                }else{
                                    temp.put(entry.field.getName(), macDecToHex(strings));
                                }
                                // TODO 后续如需格式化其他类型 如 ：IP 等 再修改
                            }else{
                                //600.0.80.86.150.126.157
                                StringBuffer sb = new StringBuffer();
                                int star = Integer.parseInt(sub[0]);
                                int length = Integer.parseInt(sub[1]);
                                for (int i = star; i < star+length; i++) {
                                    sb.append(k[i]);
                                    if(i < (star+length)-1){
                                        sb.append(".");
                                    }
                                }
                                temp.put(entry.field.getName(), sb.toString());
                            }
                        }
                    }

                }

            }
            if (temp.isEmpty()) {
                continue;
            }
            if (!emptyValue || (records.isEmpty() && valueSize == index)) {
                records.add(temp);
            }
        }
        return records;
    }

    /**
    * @Author Liuxh
    * @Description // 十进制Mac地址转为十六进制Mac地址
    * @Date 18:03 2020/6/19
    * @Param [split]
    * @return java.lang.String
    **/
    public  String macDecToHex(String[] split){

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            int num = Integer.parseInt(split[i]);
            if(num>255){
                logger.info("数字大于255，不符合转换条件：{}",num);
                return null;
            }else{
                String a = Integer.toHexString(Integer.parseInt(split[i]));
                sb.append(a);
                if(i < split.length-1){
                    sb.append(":");
                }
            }
        }
        return sb.toString();
    }
    public static String[] arraySub(String[] data,int startIdex,int len){
        //600.0.80.86.150.178.125
        String[] strings=new String[len];
        int j=0;
        for(int i=startIdex;i< startIdex+len;i++){
            strings[j]=data[i];
            j++;
        }
        return strings;
    }
}
